package thoven.achievement.net.jsonutil.action

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.ui.Messages
import thoven.achievement.net.jsonutil.service.JsonCleaner
import thoven.achievement.net.jsonutil.service.JsonFormatter

/**
 * 格式化 JSON 的编辑器操作
 */
class FormatJsonAction : AnAction() {
    
    override fun actionPerformed(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR) ?: return
        val project = e.project ?: return
        val document = editor.document
        
        val selectionModel = editor.selectionModel
        val selectedText = selectionModel.selectedText
        
        if (selectedText.isNullOrBlank()) {
            Messages.showWarningDialog(
                project,
                "请选择要格式化的 JSON 文本",
                "JSON 格式化"
            )
            return
        }
        
        // 先清理，再格式化
        val cleanResult = JsonCleaner.clean(selectedText)
        if (cleanResult.isFailure) {
            Messages.showErrorDialog(
                project,
                "清理 JSON 失败: ${cleanResult.exceptionOrNull()?.message}",
                "JSON 格式化错误"
            )
            return
        }
        
        val cleanedJson = cleanResult.getOrNull() ?: return
        val formatResult = JsonFormatter.format(cleanedJson)
        
        if (formatResult.isSuccess) {
            val formattedJson = formatResult.getOrNull() ?: return
            
            WriteCommandAction.runWriteCommandAction(project) {
                document.replaceString(
                    selectionModel.selectionStart,
                    selectionModel.selectionEnd,
                    formattedJson
                )
            }
        } else {
            Messages.showErrorDialog(
                project,
                "格式化失败: ${formatResult.exceptionOrNull()?.message}",
                "JSON 格式化错误"
            )
        }
    }
    
    override fun update(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR)
        val hasSelection = editor?.selectionModel?.hasSelection() == true
        e.presentation.isEnabledAndVisible = hasSelection
    }
}

